package com.smsc.headend.task.engine.task;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.AbstractFtp;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ssh.Sftp;
import com.smsc.headend.common.constant.Constant;
import com.smsc.headend.common.utils.DesEncrypt;
import com.smsc.headend.task.engine.ftp.config.SftpUtils;
import com.smsc.headend.task.engine.manager.DdsFilterMdmDataManager;
import com.smsc.headend.task.engine.service.asset.AssetService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author xiaosc
 * @date 2021/11/25 11:37
 */
@Component
@EnableScheduling
@Slf4j
public class MultiSpeakFileTask {

    @Autowired
    SftpUtils sftpUtils;

    @Autowired
    AssetService assetService;

    @Value("${sftp.localDir}")
    private String filePath;

    private final static String FTP = "FTP";
    private final static String XML = "xml";
    private final static String CSV = "csv";

    @Scheduled(fixedRate = 120000)
    public void uploadFileToFtp() {
        String multiSpeakFlag = assetService.getSystemProperty("DDS_MULTISPEAK_SWITCH");
        if (Constant.FALSE.equalsIgnoreCase(multiSpeakFlag)) {
            return;
        }
        log.info("started upload file to oracle mdm ftp server");
        String localFilePath = assetService.getSystemProperty("DDS_MULTISPEAK_LOCAL_PATH");
        String ftpType = assetService.getSystemProperty("DDS_MULTISPEAK_FTP_TYPE");
        String remotePath = assetService.getSystemProperty("DDS_MULTISPEAK_FTP_PATH");
        String hostName = assetService.getSystemProperty("DDS_MULTISPEAK_FTP_HOSTNAME");
        String port = assetService.getSystemProperty("DDS_MULTISPEAK_FTP_PORT");
        String username = assetService.getSystemProperty("DDS_MULTISPEAK_FTP_USERNAME");
        String password = assetService.getSystemProperty("DDS_MULTISPEAK_FTP_PASSWORD");
        DesEncrypt des = new DesEncrypt();
        if (StrUtil.isNotEmpty(password)) {
            password = des.getDesString(password);
        }
        AbstractFtp ftp;
        try {
            if (FTP.equals(ftpType)) {
                ftp = new Ftp(hostName, Convert.toInt(port), username, password);
            } else {
                ftp = new Sftp(hostName, Convert.toInt(port), username, password);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("ftp connect fail");
            return;
        }
        if (StrUtil.isEmpty(localFilePath)) {
            localFilePath = filePath;
        }
        List<File> files = FileUtil.loopFiles(localFilePath);
        String finalLocalFilePath = localFilePath;

        String multiSpeakFileIsXml = assetService.getSystemProperty("DDS_MULTISPEAK_FILE_IS_XML");
        String fileType = CSV;
        if (Constant.TRUE.equalsIgnoreCase(multiSpeakFileIsXml)) {
            fileType = XML;
        }
        String finalFileType = fileType;
        files.stream().forEach(file -> {
            if (file.getName().toLowerCase().endsWith(finalFileType)) {
                String destPath = remotePath;
                if (file.getName().startsWith(DdsFilterMdmDataManager.MULTISPEAK_MIN)) {
                    destPath += DdsFilterMdmDataManager.MULTISPEAK_MIN_FOLDER;
                } else if (file.getName().startsWith(DdsFilterMdmDataManager.MULTISPEAK_DAY)) {
                    destPath += DdsFilterMdmDataManager.MULTISPEAK_DAY_FOLDER;
                } else if (file.getName().startsWith(DdsFilterMdmDataManager.MULTISPEAK_MONTH)) {
                    destPath += DdsFilterMdmDataManager.MULTISPEAK_MONTH_FOLDER;
                } else if (file.getName().startsWith(DdsFilterMdmDataManager.MULTISPEAK_EVENTS)) {
                    destPath += DdsFilterMdmDataManager.MULTISPEAK_EVENTS_FOLDER;
                }
                boolean upload = ftp.upload(destPath, file);
                if (upload) {
                    // bak
                    String bakFilePath = file.getPath().replaceAll(finalLocalFilePath, finalLocalFilePath + "multispeak-bak/").replaceAll(finalFileType, "bak");
                    FileUtil.move(file, FileUtil.file(bakFilePath), true);
                }
            }
        });
        try {
            ftp.close();
        } catch (IOException e) {
            log.error("close ftp connect error");
        }
    }

    @Scheduled(initialDelay = 30000, fixedRate = 120000)
    public void uploadXmlFileToEipFtp() {
        String eipSwitch = assetService.getSystemProperty("DDS_EIP_SWITCH");
        if (Constant.FALSE.equalsIgnoreCase(eipSwitch)) {
            return;
        }
        log.info("started upload xml file to eip ftp server");
        String localFilePath = assetService.getSystemProperty("DDS_EIP_LOCAL_PATH");
        String ftpType = assetService.getSystemProperty("DDS_EIP_FTP_TYPE");
        String remotePath = assetService.getSystemProperty("DDS_EIP_FTP_PATH");
        String hostName = assetService.getSystemProperty("DDS_EIP_FTP_HOSTNAME");
        String port = assetService.getSystemProperty("DDS_EIP_FTP_PORT");
        String username = assetService.getSystemProperty("DDS_EIP_FTP_USERNAME");
        String password = assetService.getSystemProperty("DDS_EIP_FTP_PASSWORD");
        String meterReadsFolder = assetService.getSystemProperty("DDS_EIP_METER_READS_FOLDER");
        String eventFolder = assetService.getSystemProperty("DDS_EIP_EVENT_FOLDER");
        DesEncrypt des = new DesEncrypt();
        if (StrUtil.isNotEmpty(password)) {
            password = des.getDesString(password);
        }
        Ftp ftp = null;
        Sftp sftp = null;
        try {
            if (FTP.equals(ftpType)) {
                ftp = new Ftp(hostName, Convert.toInt(port), username, password);
                ftp.setBackToPwd(true);
            } else {
                sftp = new Sftp(hostName, Convert.toInt(port), username, password);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("{} connect fail", ftpType);
            return;
        }
        if (StrUtil.isEmpty(localFilePath)) {
            localFilePath = filePath;
        }
        List<File> files = FileUtil.loopFiles(localFilePath);
        for (File file : files) {
            try {
                String destPath = remotePath;
                if (file.getName().toLowerCase().endsWith(XML)) {
                    if (file.getName().startsWith(DdsFilterMdmDataManager.EIP_METER_READS)) {
                        destPath += meterReadsFolder;
                    }
                    if (file.getName().startsWith(DdsFilterMdmDataManager.EIP_EVENTS)) {
                        destPath += eventFolder;
                    }
                    boolean upload;
                    if (null != ftp) {
                        upload = ftp.upload(destPath, file);
                    } else {
                        upload = sftp.upload(destPath, file);
                    }
                    if (upload) {
                        log.info("file upload {} successful", file.getName());
                        // bak
                        String bakPath = file.getParent() + "/bak/" + file.getName();
                        bakPath = bakPath.replace(".xml", ".bak");
                        FileUtil.move(file, FileUtil.file(bakPath), true);
                    } else {
                        log.error("file upload {} failed", file.getName());
                    }
                }
            } catch (Exception e) {
                log.error("file upload {} exception,{}", file.getName(), e);
            }

        }
        try {
            if (null != ftp) {
                ftp.close();
            }
            if (null != sftp) {
                sftp.close();
            }
        } catch (IOException e) {
            log.error("close ftp/sftp connect error");
        }
    }
}
